package com.is2.patchinglife.activity;

import java.io.File;
import java.util.Date;
import com.is2.patchinglife.R;
import com.is2.patchinglife.manager.LocalDataManager;

import android.app.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class LoadingActivity extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// shows activity interface
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading);
		
		// execute loading operations
		IntentLauncher launcher = new IntentLauncher();
		launcher.start();
	
	}
	
	private class IntentLauncher extends Thread{
		
		private int SLEEP_TIME = 5;		// min activity showtime
			
		public void run(){
			try{
				
				
				// set current time
				Date now = new Date();
				long start = now.getTime();
				
				// setting LOCAL FILE manager (load "guest" files)
				LocalDataManager.parseLocalData(getApplicationContext(),"");

				// check auto-login
				Intent menu_intent = null;
				String loggedUser = LocalDataManager.getConf().getCookieValue();
				
				File gotTrophyFile = new File("got_trophy"+loggedUser+".json");
				File configFile = new File("config"+loggedUser+".json");
				if(!gotTrophyFile.exists() || !configFile.exists()){
					LocalDataManager.getConf().setCookieValue("");
					loggedUser = "";
					LocalDataManager.saveConf(null);
				}
				
				// GUEST MODE (open login activity)
				if(loggedUser == null || loggedUser.equals("")){
					menu_intent = new Intent(LoadingActivity.this,LoginActivity.class);
					
				// USER MODE (open main menu activity)
				}else{
					// load user specific files
					LocalDataManager.parseConf(loggedUser);
					LocalDataManager.parseGotTrophy(loggedUser);
					menu_intent = new Intent(LoadingActivity.this,MainMenuActivity.class);
					
				}
				
				// wait end of interval
				long offset = now.getTime()-start;
				Thread.sleep(SLEEP_TIME*1000-offset);
				
				// start menu and destroy activity
				LoadingActivity.this.startActivity(menu_intent);
				LoadingActivity.this.finish();	
				
			}catch(Exception e){Log.e("LOADING_ACTIVITY",e.getMessage());}
		}
	}

}
